#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Licensed Materials - Property of tenxcloud.com
# (C) Copyright 2020 TenxCloud. All Rights Reserved.
# 2020-05-31 @author lizhen

from flask import current_app
from data_set_api.root import db

import enum
import os


class DataSetPhase(enum.Enum):
    raw = 0
    processed = 1
    processing = 2


class DataSet(db.Model):
    __tablename__ = 'data_set'

    id = db.Column(db.String(8), primary_key=True)
    create_at = db.Column(db.DateTime, nullable=False)
    update_at = db.Column(db.DateTime, nullable=True)
    create_by = db.Column(db.String(8), nullable=False)
    public = db.Column(db.Boolean, nullable=False, default=False)
    name = db.Column(db.String(20), nullable=False)
    description = db.Column(db.String(100), nullable=True)
    phase = db.Column(db.Enum(DataSetPhase), nullable=False, default=DataSetPhase.raw)
    attribute = db.Column(db.SmallInteger, nullable=False, default=0)
    files = db.relationship('File', backref='data_set', lazy=True, passive_deletes=True)

    def to_dict(self):
        return {
            'id': self.id,
            'createAt': self.create_at,
            'updateAt': self.update_at,
            'createBy': self.create_by,
            'public': self.public,
            'name': self.name,
            'detail': self.description,
            'nfs-server': current_app.config['NFS_SERVER_ADDRESS'],
            'nfs-path': os.path.join(
                current_app.config['NFS_SERVER_EXPOSED_PATH'], self.id),
            'phase': self.phase,
            'attribute': self.attribute,
            'images': [image.to_dict() for image in self.files] if self.files else [],
        }


class File(db.Model):
    __tablename__ = 'file'

    id = db.Column(db.String(8), primary_key=True)
    create_at = db.Column(db.DateTime, nullable=False)
    update_at = db.Column(db.DateTime, nullable=True)
    filename = db.Column(db.String(20), nullable=False)
    suffix = db.Column(db.String(5), nullable=False)
    mask = db.Column(db.String(128), nullable=False)
    data_set_id = db.Column(db.String(8), db.ForeignKey('data_set.id', ondelete='CASCADE'), nullable=False)

    def to_dict(self):
        return {
            'id': self.id,
            'createAt': self.create_at,
            'updateAt': self.update_at,
            'filename': self.filename,
            'suffix': self.suffix,
            'mask': self.mask,
            'url': os.path.join(
                current_app.config['FILE_SERVER_PREFIX'],
                'datasets', self.data_set_id, 'images', self.id),
        }
